package com.ptt.sqm.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.ptt.sqm.model.AssessItem;
import com.ptt.sqm.model.AssessItemChoice5018;
import com.ptt.sqm.model.AssessItemList;
import com.ptt.sqm.model.AssessSubject5019;
import com.ptt.sqm.model.AssessSuggestion5034;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.model.AssessTranList;
import com.ptt.sqm.model.InsertAssessTranResult;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.model.SaveDraftAssessTranResult;
import com.ptt.sqm.model.SuggestionImage;
import com.ptt.sqm.model.SummaryAssess;
import com.ptt.sqm.model.UpdateAssessTranResult;
import com.ptt.sqm.session.SavedAssessTran;
import com.ptt.sqm.session.SavedItemAssess;
import com.ptt.sqm.session.SavedSummaryAssess;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WebserviceUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DecrementCallback;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqm.ws.UploadCall;
import com.ptt.sqmonmobile.R;

/**
 * A simple {@link Fragment} subclass. Activities that contain this fragment
 * must implement the
 * {@link SummaryAssessFragment.OnFragmentInteractionListener} interface to
 * handle interaction events. Use the {@link SummaryAssessFragment#newInstance}
 * factory method to create an instance of this fragment.
 * 
 */
public class SummaryAssessFragment extends DefaultFragment implements AsyncResponse, DecrementCallback {

	private static SummaryAssessFragment fragment;

	private OnFragmentInteractionListener mListener;

	// Create Webservice class object
	private DefaultTask mTask = null;

	private UploadCall uploadCall = null;

	private View textEntryView;

	private Map<String, SummaryAssess> summaryAssess = new TreeMap<String, SummaryAssess>();

	private SavedAssessTran savedTranPref;

	private AssessItemList items;

	private AssessTran saveAssessTran;

	private String projCycleStationId;

	private boolean isSubmit;

	private View mProgressView;

	private View mContentView;

	private int cnt;

	private boolean canBack;
	
	// For set AssessTran (SubjectName, ItemName)
	Map<String, String> subjectMap = new TreeMap<String, String>();
	Map<String, String> itemChoiceMap = new TreeMap<String, String>();

	public static SummaryAssessFragment newInstance(int sectionNumber, AssessItemList items, AssessTran saveAssessTran) {
		fragment = new SummaryAssessFragment(items, saveAssessTran);
		Bundle args = new Bundle();
		args.putInt(AppUtil.ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);

		return fragment;
	}

	public SummaryAssessFragment(AssessItemList items, AssessTran saveAssessTran) {
		// Required empty public constructor
		this.items = items;
		this.saveAssessTran = saveAssessTran;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		Login login = session.getUserDetails();
		projCycleStationId = items.projectId + AppUtil.UNDER_SCROLL + items.cycleAssessId + AppUtil.UNDER_SCROLL + items.stationId + AppUtil.UNDER_SCROLL + login.User_Group_Code;

		// handle Back Pressed
		handleBackPressed();

		// Loading...
		mProgressView = view.findViewById(R.id.progress);
		mContentView = view.findViewById(R.id.container);

		// Load Shared Preferences - SavedAssessTran
		savedTranPref = new SavedAssessTran(getActivity().getApplicationContext());

		// is AssessTran submitted?
		if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
			isSubmit = true;

		// Set AssessTran (SubjectName, ItemName)
		setSubjectAndItemName();

		// Sample Data
		((TextView) getView().findViewById(R.id.station)).setText(items.stationId + AppUtil.SPACE + items.stationName);
		((TextView) getView().findViewById(R.id.project_assess)).setText(items.projectName);
		((TextView) getView().findViewById(R.id.cycle_assess)).setText(items.cycle);
		((TextView) getView().findViewById(R.id.pbl)).setText(items.locationId);
		TextView assessDate = (TextView) view.findViewById(R.id.assess_date);
		TextView fullnameAssess = (TextView) view.findViewById(R.id.fullname_assess);
		TextView groupAssess = (TextView) view.findViewById(R.id.group_assess);

		assessDate.setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.CreateDate));
		if (login.isAdmin()) {
			fullnameAssess.setText(saveAssessTran.UserName);
			groupAssess.setText(saveAssessTran.UserTypeName);
		} else {
			fullnameAssess.setText(login.User_Name);
			groupAssess.setText(login.User_Group_Name);
		}

		setSummaryScore();

		Button saveCmtBtn = (Button) getView().findViewById(R.id.save_assess);
		if (isSubmit) {
			saveCmtBtn.setVisibility(Button.GONE);
			((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.VISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setVisibility(TextView.VISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.SubmitDate));
		} else {
			((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.INVISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setVisibility(TextView.INVISIBLE);
		}

		saveCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				canBack = false;
				WidgetUtil.showProgress(mContentView, mProgressView, true);

				// Save Images on Server
				saveImageOnServer();
			}
		});

		Button summarySgtCmtBtn = (Button) getView().findViewById(R.id.summary_suggestion);
		summarySgtCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit).addToBackStack(null)
					.replace(R.id.container, SummarySuggestionFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, saveAssessTran)).commit();

			}
		});

		Button subjectCmtBtn = (Button) getView().findViewById(R.id.subject_assess);
		subjectCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				// fragmentTransaction.setCustomAnimations(R.anim.pop_enter,
				// R.anim.pop_exit).addToBackStack(null)
				// .replace(R.id.container,
				// MakeAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER),
				// items, true)).commit();
				fragmentTransaction.addToBackStack(null).replace(R.id.container, MakeAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, true)).commit();

			}
		});

		Button cancelCmtBtn = (Button) getView().findViewById(R.id.cancel_assess);
		cancelCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder cancelConfirm = new AlertDialog.Builder(getActivity());

				cancelConfirm.setTitle(getString(R.string.alert_confirm_cancel));
				cancelConfirm.setNegativeButton("Cancel", null);
				cancelConfirm.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {

						FragmentManager fragmentManager = getFragmentManager();
						WidgetUtil.backPress(getActivity());

					}
				});
				cancelConfirm.show();

			}
		});
	}

	private void setSummaryScore() {
		// TODO Auto-generated method stub
		// summaryAssess = (HashMap<String, SummaryAssess>)
		// getArguments().getSerializable(AppUtil.SUMMARY_KEY);
		SavedSummaryAssess saveSummaryPref = new SavedSummaryAssess(getActivity().getApplicationContext());
		summaryAssess = saveSummaryPref.loadMap(projCycleStationId);
		LayoutInflater factory = LayoutInflater.from(getActivity());
		textEntryView = factory.inflate(R.layout.summary_row, null);

		TableLayout table = (TableLayout) getView().findViewById(R.id.summary_table);

		int grandNetTotal = 0;
		int grandWeightTotal = 0;
		int grandPercent = 0;

		table.removeAllViews();
		for (String subject : summaryAssess.keySet()) {
			// Inflate your row "template" and fill out the
			// fields.
			TableRow row = (TableRow) LayoutInflater.from(SummaryAssessFragment.this.getActivity()).inflate(R.layout.summary_row, null);

			((TextView) row.findViewById(R.id.subject_name)).setText(summaryAssess.get(subject).subjectName);
			if (summaryAssess.get(subject).netTotal != 0) {
				((TextView) row.findViewById(R.id.net_total)).setText(String.valueOf(summaryAssess.get(subject).subjectTotal));
				((TextView) row.findViewById(R.id.sum_total)).setText(String.valueOf(summaryAssess.get(subject).weightTotal));
				((TextView) row.findViewById(R.id.percent)).setText(String.valueOf(summaryAssess.get(subject).percentTotal));

				grandNetTotal += summaryAssess.get(subject).subjectTotal;
				grandWeightTotal += summaryAssess.get(subject).weightTotal;
			}

			table.addView(row);
		}
		table.requestLayout();

		((TextView) getView().findViewById(R.id.grand_net_total)).setText(String.valueOf(grandNetTotal));
		((TextView) getView().findViewById(R.id.grand_sum_total)).setText(String.valueOf(grandWeightTotal));
		((TextView) getView().findViewById(R.id.grand_percent)).setText(String.valueOf(Math.round(((float) grandWeightTotal / (float) grandNetTotal) * 100)));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View rootView = inflater.inflate(R.layout.summary_assess, container, false);
		return rootView;
	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Uri uri) {
		if (mListener != null) {
			mListener.onFragmentInteraction(uri);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		((MainActivity) activity).onSectionAttached(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER));
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Uri uri);
	}

	private void setSubjectAndItemName() {
		// TODO Auto-generated method stub
		for (AssessItem assessItem : items.assessItem) {
			if (!subjectMap.containsKey(assessItem.CycleAssessSubjectId))
				subjectMap.put(assessItem.CycleAssessSubjectId, assessItem.AssessSubjectName);
			if (!itemChoiceMap.containsKey(assessItem.CycleAssessSubjectId))
				itemChoiceMap.put(assessItem.AssessItemId, assessItem.AssessItemName);
		}

	}

	private void saveAssessTranStep4_SaveDraft() {
		saveAssessTran.Status = AppUtil.ASSESS_STATUS_DRAFT;
		int grandWeightTotal = 0;
		for (SummaryAssess summary : summaryAssess.values())
			if (summary.netTotal != 0)
				grandWeightTotal += summary.weightTotal;
		saveAssessTran.TotalPoint = grandWeightTotal;

		// First Page Load
		PropertyInfo projProp = new PropertyInfo();
		projProp.setName(AppUtil.ProjectId);
		projProp.setValue(items.projectId);
		projProp.setType(String.class);

		PropertyInfo cycleProp = new PropertyInfo();
		cycleProp.setName(AppUtil.CycleAssessId);
		cycleProp.setValue(items.cycleAssessId);
		cycleProp.setType(String.class);

		PropertyInfo ResourceProp = new PropertyInfo();
		ResourceProp.setName(AppUtil.UserTypeId);
		ResourceProp.setValue(saveAssessTran.UserTypeId);
		ResourceProp.setType(String.class);

		PropertyInfo StationProp = new PropertyInfo();
		StationProp.setName(AppUtil.STATIONID);
		StationProp.setValue(items.stationId);
		StationProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_getassesstranlastupdate), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(ResourceProp, projProp, cycleProp, StationProp);
	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(getString(R.string.method_savedraftassesstran))) {
				getSaveDraft(method, output);
			} else if (method.equals(getString(R.string.method_getassesstran))) {
				getAssessTran(method, output);
			} else if (method.equals(getString(R.string.method_getassesstranlastupdate))) {
				getAssessTranLastUpdate(method, output);
			}
		} catch (Exception e) {
			Log.i("error", e.toString());
		}
	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(getString(R.string.http_url))) {
				UploadImage(method, output, objects);
			}
		} catch (Exception e) {
			Log.i("error", e.toString());
		}

	}

	private void getAssessTranLastUpdate(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			AssessTranList assessTranLastUpdate = (AssessTranList) gson.fromJson((String) output, AssessTranList.class);
			if (assessTranLastUpdate != null)
				saveAssessTran.RESOURCE_ID = assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).RESOURCE_ID;

			PropertyInfo saveAssessProp = new PropertyInfo();
			saveAssessProp.setName(AssessTran.AssessTranParam);
			saveAssessProp.setValue(WebserviceUtil.getAssessTran(AssessTran.AssessTranParam, saveAssessTran));
			saveAssessProp.setType(SoapObject.class);

			mTask = new DefaultTask(com, getString(R.string.method_savedraftassesstran));
			mTask.delegate = fragment;
			mTask.execute(saveAssessProp);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}
	}

	private void getAssessTran(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			saveAssessTran = (AssessTran) gson.fromJson((String) output, AssessTran.class);

			saveAssessTran.StationName = items.stationName;
			saveAssessTran.ProjectName = items.projectName;
			saveAssessTran.CycleName = items.cycle;

			generateAssessItem();
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
		}

		canBack = true;
		WidgetUtil.showProgress(mContentView, mProgressView, false);
	}

	private void getAssessTranLastUpdate(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			AssessTranList assessTranLastUpdate = (AssessTranList) gson.fromJson((String) output, AssessTranList.class);
			if (assessTranLastUpdate != null) {
				saveAssessTran.RESOURCE_ID = assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).RESOURCE_ID;
				if (assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).Status.equals(AppUtil.ASSESS_STATUS_SUBMIT)) {

					Toast.makeText(getActivity(), getString(R.string.alert_already_submit), Toast.LENGTH_LONG).show();

					savedTranPref.ClearSavedAssessTran(projCycleStationId);
					isSubmit = false;

					PropertyInfo projProp = new PropertyInfo();
					projProp.setName(AppUtil.ProjectId);
					projProp.setValue(items.projectId);
					projProp.setType(String.class);

					PropertyInfo cycleProp = new PropertyInfo();
					cycleProp.setName(AppUtil.CycleAssessId);
					cycleProp.setValue(items.cycleAssessId);
					cycleProp.setType(String.class);

					PropertyInfo ResourceProp = new PropertyInfo();
					ResourceProp.setName(AppUtil.RESOURCE_ID);
					ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
					ResourceProp.setType(String.class);

					PropertyInfo StationProp = new PropertyInfo();
					StationProp.setName(AppUtil.STATIONID);
					StationProp.setValue(items.stationId);
					StationProp.setType(String.class);

					mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
					mTask.delegate = this;
					mTask.execute(ResourceProp, projProp, cycleProp, StationProp);
					return;
				}
			}

			PropertyInfo saveAssessProp = new PropertyInfo();
			saveAssessProp.setName(AssessTran.AssessTranParam);
			saveAssessProp.setValue(WebserviceUtil.getAssessTran(AssessTran.AssessTranParam, saveAssessTran));
			saveAssessProp.setType(SoapObject.class);

			mTask = new DefaultTask(com, getString(R.string.method_savedraftassesstran));
			mTask.delegate = fragment;
			mTask.execute(saveAssessProp);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}
	}

	private void generateAssessItem() {
		// TODO Auto-generated method stub
		if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
			isSubmit = true;
		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019) {
			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoice) {
				subject.Items.get(0).AssessItemChoiceMap.put(item.AssessItemId, item);
				if (!saveAssessTran.Subjects.get(0).AssessSubject5019Map.containsKey(item.CycleAssessSubjectId))
					saveAssessTran.Subjects.get(0).AssessSubject5019Map.put(item.CycleAssessSubjectId, subject);
				item.AssessSubjectName = subjectMap.get(item.CycleAssessSubjectId);
				item.AssessItemName = itemChoiceMap.get(item.AssessItemId);
				if (item.Suggestions != null) {
					for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034) {
						item.Suggestions.get(0).AssessSuggestion5034Map.put(AppUtil.NEW_SUGGESTION + suggestion.AssessSuggestionIndex, suggestion);
					}
				}

			}
		}
		savedTranPref.saveMap(projCycleStationId, saveAssessTran);

	}

	private void getSaveDraft(String method, Object output) {
		// TODO Auto-generated method stub
		output = "{" + output + "}";
		try {
			SaveDraftAssessTranResult SaveDraftAssessTranResult = (SaveDraftAssessTranResult) gson.fromJson((String) output, SaveDraftAssessTranResult.class);

			Toast.makeText(getActivity(), getString(R.string.alert_save_draft), Toast.LENGTH_LONG).show();
			savedTranPref.ClearSavedAssessTran(projCycleStationId);
			isSubmit = false;

			PropertyInfo projProp = new PropertyInfo();
			projProp.setName(AppUtil.ProjectId);
			projProp.setValue(items.projectId);
			projProp.setType(String.class);

			PropertyInfo cycleProp = new PropertyInfo();
			cycleProp.setName(AppUtil.CycleAssessId);
			cycleProp.setValue(items.cycleAssessId);
			cycleProp.setType(String.class);

			PropertyInfo ResourceProp = new PropertyInfo();
			ResourceProp.setName(AppUtil.RESOURCE_ID);
			ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
			ResourceProp.setType(String.class);

			PropertyInfo StationProp = new PropertyInfo();
			StationProp.setName(AppUtil.STATIONID);
			StationProp.setValue(items.stationId);
			StationProp.setType(String.class);

			mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
			mTask.delegate = this;
			mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	private void saveImageOnServer() {
		// TODO Auto-generated method stub
		List<SuggestionImage> deviceImages = new ArrayList<SuggestionImage>();
		List<SuggestionImage> serverImages = new ArrayList<SuggestionImage>();
		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019Map.values()) {

			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoiceMap.values()) {

				if (item.AssessChoicePoint.length() != 0)

					if (item.Suggestions != null && item.Suggestions.size() != 0) {
						for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034Map.values()) {
							if (suggestion.Images != null && suggestion.Images.size() != 0) {
								for (SuggestionImage image : suggestion.Images.get(0).SuggestionImage) {
									// CR 107, 108
									if (image.CreatedDt == null || image.CreatedDt.length() == 0) {
										deviceImages.add(image);
									} else {
										serverImages.add(image);
									}
								}

								if (serverImages.size() != 0) {
									for (SuggestionImage image : serverImages) {
										suggestion.Images.get(0).SuggestionImage.remove(image);
									}
									serverImages = new ArrayList<SuggestionImage>();
								}

							}
						}
					}
			}
		}

		if (deviceImages.size() != 0) {
			setCount(deviceImages.size());
			for (SuggestionImage image : deviceImages) {
				uploadCall = UploadCall.getInstance();

				PropertyInfo nameProp = new PropertyInfo();
				nameProp.setValue(image.FILE_SAVE_NAME);
				nameProp.setType(String.class);

				PropertyInfo bitmapProp = new PropertyInfo();
				bitmapProp.setValue(WidgetUtil.getImageOnDevice(getActivity(), image.FILE_SAVE_NAME));
				bitmapProp.setType(Bitmap.class);

				mTask = new DefaultTask(uploadCall, getString(R.string.http_url), image);
				mTask.delegate = fragment;
				mTask.execute(nameProp, bitmapProp);

				Log.i("save image count", "T");
			}
		} else {
			onDecrementCount();
		}

	}

	private void UploadImage(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		SuggestionImage image = (SuggestionImage) objects[0];

		try {
			int serverResponseCode = Integer.parseInt((String) output);
			if (serverResponseCode == 200) {
				onDecrementCount();
			} else {
				Toast.makeText(getActivity(), getString(R.string.alert_save_image_failed), Toast.LENGTH_LONG).show();
				canBack = true;
				WidgetUtil.showProgress(mContentView, mProgressView, false);
			}

		} catch (Exception e) {
			Toast.makeText(getActivity(), getString(R.string.alert_save_image_failed), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}

	}

	private void handleBackPressed() {
		// TODO Auto-generated method stub
		getView().setFocusableInTouchMode(true);
		getView().requestFocus();
		getView().setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if (canBack) {
						WidgetUtil.backPress(getActivity());
					} else {
						return true;
					}
				}

				return false;
			}
		});
	}

	@Override
	public void setCount(int cnt) {
		// TODO Auto-generated method stub
		this.cnt = cnt;
	}

	@Override
	public void onDecrementCount() {
		// TODO Auto-generated method stub
		cnt--;
		if (cnt <= 0) {
			Log.i("saveAssessTranStep4_SaveDraft", "PASS");
			saveAssessTranStep4_SaveDraft();
		}
	}

	@Override
	public void onDecrementCount(View view, int cnt) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDecrementCount(boolean flag) {
		// TODO Auto-generated method stub

	}
}
